//处理权限验证相关的东西
import {router,addRoutes} from '~/router'
import {getToken} from '~/composables/auth'
import {toast,showFullLoading,hideFullLoading} from '~/composables/util'
import store from './store'


//全局前置配置 to:到哪里去，from:从哪里来
let hasGetInfo = false;//防止重复性加载请求数据
router.beforeEach( async (to, from, next) => {
  //显示Loading
  showFullLoading()
//   console.log('全局前置配置') 
const token = getToken()
//没有登录，强制跳转回登录页
if(!token && to.path != '/login'){
    toast('请先登录','error')
    return next({ path:'/login' })
}
if(token && to.path == '/login'){
    toast('请勿重复操作','error   ')
    // 返回从哪里来否则会返回后台首页
    return next({path:from.path?from.path:'/'})
}

let hasNewRoutes = false 

//如果用户登录就自动获取用户信息，并存储在vuex中
  if(token && !hasGetInfo){
   let {menus} =  await store.dispatch("getinfo")
   hasGetInfo = true
    //动态添加路由
    hasNewRoutes = addRoutes(menus)
  }

  //设置标题界面
  let title = (to.meta.title?to.meta.title:'')+'-李心雨商城后台'
  document.title = title
  //放行
  hasNewRoutes ? next(to.fullPath) :next() 
})
//Loading比较快
router.afterEach((to,from)=>hideFullLoading())